pp108 : Optimizing XPath Expression Usage

Optimizing XPath Expression Usage

This topic describes the best practices for using XPath expressions.

While defining XPath expressions, if you give optimized path (varying according to situations), it will improve the performance. Follow these guidelines while defining XPath expressions:

  • Understand the search scenario completely
  • Be specific while searching for specific nodes.For example, if 'weather' is your first and only one node that has the name 'weather', and you are searching for the child 'forecast' inside 'weather', give /weather/forecast instead of //weather1/forecast.
  • Use 'descendant-or-self' axis instead of //.If you write //weather, the parser will expand it to /descendant-or-self::node()/weather, that contains the expression with three location steps:
  1. Select root
  2. Select all descendants of it
  3. Select all 'weather' elements from it
    Instead, you can write the expression /descendant-or-self::weather. This is an expression with just two steps and selects the same nodeset. For more examples, refer to XPath specifications|XPath specifications.
  • While searching for a particular node that is the first of such nodes inside an XML document, useFind. findFirstMatch, because it is the fastest search mechanism available for NOM.
  • Reduce the number of lines of Java code with XPath expressions. For example, consider following XML:
    <weather xmlns:ns="http://hello.com">
        <forecast by="shilu" day="6" id="35">
            <temperature id="36" scale="F11">75</temperature>
            <humidity id="37">60</humidity>
            <temperature id="38" scale="F12">357</temperature>
            <wind id="39" scale="ns:mytype" unit="mph">33.5</wind>
            <precip id="40">Fog</precip>
        </forecast>
    </weather>
    

    If you have to select those nodes which have 'scale' attribute (along with values) that originate fromhttp://hello.com, the following expression will select those nodes:

    "//@scale[../namespace::*[local-name(.) = substring-before(../@scale,':') and . = 'http://hello.com']]/.."

Related reference

Defining XPath Expressions
XPath Parser, XPath Object and XPath Output
Understanding XPath Expressions
Using XPath API

Related information

Overview of XPath